package com.xtaller.sdboot.core.base;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.sdboot.utils.bean.JwtModel;
import com.xtaller.sdboot.utils.bean.Pageer;
import com.xtaller.sdboot.utils.helper.JsonHelper;
import com.xtaller.sdboot.utils.helper.JwtHelper;
import com.xtaller.sdboot.utils.helper.ValidatorHelper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.jsonwebtoken.Claims;
import lombok.var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author : Taller
 * @date : 2020/2/24 00:49
 * @Description : 原始控制器
 */
public class OriginalController {
    public static final Logger log = LoggerFactory.getLogger(OriginalController.class);
    @Autowired public HttpServletRequest request;

    /**
     * 向请求中加入appid
     * */
    public HttpServletRequest setAppId(HttpServletRequest request){
        request.setAttribute("appId", applicationId.get());
        return request;
    }

    /**
     * 从header中获取key数据
     * */
    public Function<String, String> header = key -> request.getHeader(key);

    /**
     * 获取请求Token数据
     * */
    public Supplier<String> token = () -> header.apply("token");

    /**
     * 从token中解析出subject
     * */
    public Supplier<JSONObject> subject = () -> {
        JwtModel jwt = JwtHelper.validateJWT(token.get());
        if (jwt.isSuccess()) {
            try {
                Claims claims = jwt.getClaims();
                String subject = claims.getSubject();
                if (ValidatorHelper.isEmpty(subject)) {
                    return null;
                }
                return JsonHelper.s2j(subject);
            } catch (Exception ex) {
                return null;
            }
        } else {
            return null;
        }
    };

    /**
     * 当前操作用户的UserId
     * */
    public Supplier<String> userId = () -> {
        var map = subject.get();
        if(map == null) {
            return null;
        }
        return map.get("userId").toString();
    };
    /**
     * 当前操作子系统的applicationId
     * */
    public Supplier<String> applicationId = () -> {
        var map = subject.get();
        if(map == null) {
            return null;
        }
        return map.get("applicationId").toString();
    };

    /**
     * 获取url下的参数 ?后的
     */
    public static Map<String, Object> convertParams2Map(HttpServletRequest request) {
        Map<String, Object> result = new HashMap(8);
        var appId = request.getAttribute("appId");
        if(appId != null){
            result.put("appId", appId);
        }
        if (request != null) {
            Enumeration paramNames = request.getParameterNames();
            while(paramNames.hasMoreElements()) {
                String paramName = (String)paramNames.nextElement();
                String[] values = request.getParameterValues(paramName);
                if (ValidatorHelper.notEmpty(values)) {
                    if (values.length == 1) {
                        result.put(paramName, values[0]);
                    } else {
                        result.put(paramName, values);
                    }
                }
            }
        }
        return result;
    }
    /**
     * 把where拿出来
     * */
    public static JSONObject findWhere(Map<String, Object> params) {
        var qw = new QueryWrapper<>();
        var where = JsonHelper.create();
        // 查询条件 a:eq:b-c:like:d
        String whereString = params.get("where") == null ? "" : params.get("where") + "";
        if (whereString.length() > 0) {
            var items = whereString.split("~");
            if (items.length > 0) {
                for (var item : items) {
                    var query = item.split(":");
                    if (query.length >= 3) {
                        where.put(query[0], query[2]);
                        // 之间
                        if (query[1].toUpperCase().equals("BETWEEN")) {
                            var s = query[2].replace("/", ":");
                            var e = query[3].replace("/", ":");
                            where.put(query[0], s + " " + e);
                        }
                    }
                }
            }
        }
        return where;
    }
    public static QueryWrapper convertMap2Wrapper(Map<String, Object> params){
        var qw = new QueryWrapper<>();
        // 查询条件 a:eq:b-c:like:d
        var whereString = params.get("where") == null ? "" : params.get("where") + "";
        if(whereString.length() > 0){
            var items = whereString.split("~");
            if(items.length > 0){
                for(var item : items){
                    var query = item.split(":");
                    if(query.length >= 3){
                        // 相等
                        if(query[1].toUpperCase().equals("EQ")){
                            qw.eq(query[0], query[2]);
                        }
                        // 模糊匹配
                        if(query[1].toUpperCase().equals("LIKE")){
                            qw.like(query[0], query[2]);
                        }
                        // 大于
                        if(query[1].toUpperCase().equals("GT")){
                            qw.gt(query[0], query[2]);
                        }
                        // 大于等于
                        if(query[1].toUpperCase().equals("GE")){
                            qw.ge(query[0], query[2]);
                        }
                        // 小于
                        if(query[1].toUpperCase().equals("LT")){
                            qw.lt(query[0], query[2]);
                        }
                        // 小于等于
                        if(query[1].toUpperCase().equals("LE")){
                            qw.le(query[0], query[2]);
                        }
                        // 不等于
                        if(query[1].toUpperCase().equals("NE")){
                            qw.ne(query[0], query[2]);
                        }
                        // 之间
                        if(query[1].toUpperCase().equals("BETWEEN")){
                            // 时间处理
                            var s = query[2].replace("/", ":");
                            var e = query[3].replace("/", ":");
                            qw.between(query[0], s, e);
                        }
                    }
                }
            }
        }
        // 排序方式
        var orderBy = params.get("orderBy") == null ? "createTime:desc" : params.get("orderBy") + "";
        var items = orderBy.split("~");
        for(var i = 0; i<items.length; i++){
            var ob = items[i].split(":");
            if(ob.length == 1){
                qw.orderByDesc(ob[0]);
            }else{
                if(ob[1].toUpperCase().equals("DESC")){
                    qw.orderByDesc(ob[0]);
                }else{
                    qw.orderByAsc(ob[0]);
                }
            }
        }
        // appId
        var appId = params.get("appId");
        if(appId != null){
            qw.eq("appId", appId);
        }
        return qw;
    }

    public JSONObject getJSONParam(HttpServletRequest request){
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 写入数据到Stringbuilder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            jsonParam = JSONObject.parseObject(sb.toString());
            // 直接将json信息打印出来
            System.out.println(jsonParam.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }

    /**
     * 获取header下的参数
     */
    public Function<String, Integer> paramInt = key -> {
        var val = header.apply(key);
        return Integer.parseInt(val == null ? "0" : val);
    };
    public Function<String, Long> paramLong = key -> {
        var val = header.apply(key);
        return Long.parseLong(val == null ? "0" : val);
    };
    /**
     * 获取url下的参数 ?后的
     */
    public Function<String, String> paramStr = key -> {
        var val = request.getParameter(key);
        return val == null ? "" : val;
    };
    /**
     * 判断数组中是否包含某个元素
     * */
    public Boolean contains(String[] arr, String val){
        Set<String> set = new HashSet<>(Arrays.asList(arr));
        return set.contains(val);
    }

    /**
     * 分页参数
     * */
    public Pageer pageer(Map<String, Object> params){
        var current = params.get("page") == null ? 1 : Integer.parseInt(params.get("page") + "");
        var limit = params.get("limit") == null ? 20 : Integer.parseInt(params.get("limit") + "");
        var p = new Pageer();
        limit = limit > 1000 ? 1000 : limit;
        p.setCurrent(current);
        p.setLimit(limit);
        return p;
    }

    /**
     * 转成layui表格
     * */
    public JSONObject formatterTable(IPage data){
        return JsonHelper.create("code", 0)
                    .put("data", data.getRecords())
                    .put("current", Integer.parseInt(data.getCurrent() + ""))
                    .put("pages", Integer.parseInt(data.getPages() + ""))
                    .put("count", Integer.parseInt(data.getTotal() + ""))
                    .put("size", Integer.parseInt(data.getSize() + ""))
                    .put("code", 0)
                    .put("msg", "读取成功");
    }
}
